package cn.tedu.sp02.item.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;
    //为了测试多台集群服务器的负载均衡,注入端口号
    @Value("${server.port}")
    private int port;

    /**
     * 根据订单id查询订单商品
     * @param orderId 订单id
     * @return JsonResult<List<Item>>
     */
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("orderId="+orderId+",port="+port);
        //添加随机延迟代码
        if (Math.random()<0.9){
            int t = new Random().nextInt(5000);
            log.info("延迟了:"+t+"毫秒");
            Thread.sleep(t);
        }
        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok().msg("port="+port).data(items);//200 port=xxx [{xx},{xx},..]
    }

    /**
     * 减少库存
     * @param items 要减少的商品
     * @return JsonResult<?>
     */
    @PostMapping("/decreaseNumber")//只处理POST请求
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        //@RequestBody注解 完整接收post请求协议体数据
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少商品库存成功");//200 "减少商品库存成功" null
    }
}
